package services

import (
	"errors"

	"gorm.io/gorm"

	"ppp/internal/config"
	"ppp/internal/models"
)

// UserService 用户服务接口
type UserService interface {
	CreateUser(req *models.CreateUserRequest) (*models.User, error)
	GetUserByID(id uint) (*models.User, error)
	UpdateUser(id uint, req *models.UpdateUserRequest) (*models.User, error)
	DeleteUser(id uint) error
	ListUsers() ([]models.User, error)
}

// userService 用户服务实现
type userService struct {
	db *gorm.DB
}

// NewUserService 创建用户服务实例
func NewUserService() UserService {
	return &userService{
		db: config.GetDB(),
	}
}

// CreateUser 创建用户
func (s *userService) CreateUser(req *models.CreateUserRequest) (*models.User, error) {
	user := &models.User{
		Name: req.Name,
		Age:  req.Age,
	}

	result := s.db.Create(user)
	if result.Error != nil {
		return nil, result.Error
	}

	return user, nil
}

// GetUserByID 根据ID获取用户
func (s *userService) GetUserByID(id uint) (*models.User, error) {
	var user models.User
	result := s.db.First(&user, id)
	if result.Error != nil {
		if errors.Is(result.Error, gorm.ErrRecordNotFound) {
			return nil, errors.New("用户不存在")
		}
		return nil, result.Error
	}
	return &user, nil
}

// UpdateUser 更新用户
func (s *userService) UpdateUser(id uint, req *models.UpdateUserRequest) (*models.User, error) {
	// 检查用户是否存在
	user, err := s.GetUserByID(id)
	if err != nil {
		return nil, err
	}

	// 更新用户信息
	user.Name = req.Name
	user.Age = req.Age

	result := s.db.Save(user)
	if result.Error != nil {
		return nil, result.Error
	}

	return user, nil
}

// DeleteUser 删除用户
func (s *userService) DeleteUser(id uint) error {
	// 检查用户是否存在
	_, err := s.GetUserByID(id)
	if err != nil {
		return err
	}

	result := s.db.Delete(&models.User{}, id)
	if result.Error != nil {
		return result.Error
	}

	return nil
}

// ListUsers 获取用户列表
func (s *userService) ListUsers() ([]models.User, error) {
	var users []models.User
	result := s.db.Find(&users)
	if result.Error != nil {
		return nil, result.Error
	}

	return users, nil
}